package com.sharein.auth.web;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sharein.auth.actions.Action;
import com.sharein.auth.actions.GetAnswer;
import com.sharein.auth.actions.GetEmail;
import com.sharein.auth.actions.GetQuestion;
import com.sharein.auth.actions.GetSignedInUser;
import com.sharein.auth.actions.IsShareinID;
import com.sharein.auth.actions.SendEmail;
import com.sharein.auth.actions.Signin;
import com.sharein.auth.actions.Signup;
import com.sharein.auth.actions.StartPage;
import com.sharein.auth.actions.isValidPassword;

public class Authentification extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public HashMap<String, Action> actions;

	@Override
	public void init() throws ServletException {
		actions = new HashMap<String, Action>();
		actions.put("signup", new Signup());
		actions.put("signin", new Signin());
		actions.put("isShareinID", new IsShareinID());
		actions.put("isValidPassword", new isValidPassword());
		actions.put("startpage", new StartPage());
		actions.put("getquestion", new GetQuestion());
		actions.put("getanswer", new GetAnswer());
		actions.put("getemail", new GetEmail());
		actions.put("sendemail", new SendEmail());
		actions.put("getsignedinuser", new GetSignedInUser());
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
 		int i = uri.lastIndexOf('/');
 		int j = uri.lastIndexOf(".do");
 		String key;
 		if(j!=-1 || i+1 == uri.length()) {
	 		if(i+1 == uri.length()) key = "startpage"; 
	 		else key = uri.substring(i+1, j);
	 		Action a = actions.get(key);
	 		if (a != null) {
	 			if(a.execute(request, response)) System.out.println(key + " action is successfully executed.");
	 			else System.out.println("A problem occured in " + key + " action execution!");
	 		}
	 		else System.out.println("Action \"" + key + "\"does not exist");
 		}
 		else key = uri.substring(i);
 		System.out.println("Authentification servlet is called with " + key + " key.");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
